package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.DTResponseDto;
import com.hualude.roadsign.dto.NoticeListDto;
import com.hualude.roadsign.repository.NoticeAddRepository;
import com.hualude.roadsign.repository.NoticeListRepository;
import com.hualude.roadsign.repository.UserRepository;
import com.hualude.roadsign.service.NoticeAppService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by pjn on 2017/4/20.
 */
@Service
public class NoticeAppServiceImpl implements NoticeAppService {
    @Resource
    private NoticeAddRepository noticeAddRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private NoticeListRepository noticeListRepository;

    public DTResponseDto getNoticeAppSended4DT(DTRequestDto dtRequestDto, Integer userId) throws Exception {
        String search = dtRequestDto.getSearch();
        List<NoticeListDto> dto4DTs = noticeAddRepository.getNoticeAppSended4DT(search, dtRequestDto, userId);
        Integer count = noticeAddRepository.getNoticeAppSendedCount4DT(search, userId);
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    @Transactional
    public String addAppNotice(Integer createUserId, String noticeTitle, String noticeContext, String noticePic) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        // System.out.println(df.format(new Date()));// new Date()为获取当前系统时间

        NoticeListDto noticeDto = new NoticeListDto();
        noticeDto.setCreateUserId(createUserId);
        noticeDto.setNoticeTitle(noticeTitle);
        noticeDto.setNoticeContent(noticeContext);
        noticeDto.setNoticeSendTime(df.format(new Date()));
        noticeDto.setNoticePic(noticePic);
        noticeDto.setNoticeType(1);
        Integer noticeId = noticeAddRepository.save(noticeDto.toAppBean()).getNoticeId();

        List<Integer> userIdDto = userRepository.getUserIds2NoticeApp();
        for (int i = 0; i < userIdDto.size(); i++) {
            NoticeListDto userNoticeDto = new NoticeListDto();
            userNoticeDto.setNoticeId(noticeId);
            userNoticeDto.setUserId(userIdDto.get(i));
            noticeListRepository.save(userNoticeDto.toUserNoticeBean());
        }
        return "";
    }

    public List<NoticeListDto> getAppPicNotice() throws Exception{
        return noticeAddRepository.getAppPicNotice();
    }

    @Override
    public Integer getIsReadNotice(Integer userId) throws Exception {
        return noticeAddRepository.getIsReadNotice(userId);
    }
}
